package cn.adelyn.blog.file.service;

import cn.adelyn.base.api.snowfalke.feign.SnowflakeFeignClient;
import cn.adelyn.blog.file.constant.FileCacheNames;
import cn.adelyn.blog.file.constant.MinioConstant;
import cn.adelyn.blog.file.dao.ShareInfoDAOService;
import cn.adelyn.blog.file.pojo.dto.InsertShareInfoDTO;
import cn.adelyn.blog.file.pojo.model.ShareInfoModel;
import cn.adelyn.common.core.cglib.CglibUtil;
import cn.adelyn.common.core.execption.AdelynException;
import cn.adelyn.common.core.response.ResponseEnum;
import cn.adelyn.common.oss.config.MinioTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ShareService {

    @Autowired
    SnowflakeFeignClient snowflakeFeignClient;

    @Autowired
    MinioTemplate minioTemplate;

    @Autowired
    ShareInfoDAOService shareInfoDAOService;

    public void insertShareInfo(InsertShareInfoDTO insertShareInfoDTO) {

        Long shareId = snowflakeFeignClient.snowflakeId().getData();

        shareInfoDAOService.insertShareInfoRedis(FileCacheNames.SHARE_ID + shareId, Long.toString(insertShareInfoDTO.getFileId()),
                insertShareInfoDTO.getInvalidTime().getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);

        ShareInfoModel shareInfoModel = CglibUtil.copy(insertShareInfoDTO, ShareInfoModel.class);
        shareInfoModel.setShareId(shareId);

        shareInfoDAOService.insertShareInfoDb(shareInfoModel);
    }

    public void deleteShareInfo(Long shareId) {
        shareInfoDAOService.deleteShareInfoDb(shareId);
    }

    public String genSharedFileDownloadUrl(Long shareId) {
        Long fileId = Long.valueOf(shareInfoDAOService.getShareInfoRedis(String.valueOf(shareId)));
        return genDownloadUrl(fileId);
    }

    public String genDownloadUrl(long fileId) {
        try {
            String downloadUrl = minioTemplate.genDownloadUrl(MinioConstant.BUCKET, MinioConstant.FILE_PATH_PREFIX + MinioConstant.PATH_SEPARATOR + fileId,
                    MinioConstant.DOWNLOAD_URL_DURATION, MinioConstant.TIME_UNIT);
            return downloadUrl;
        }catch (Exception e){
            throw new AdelynException(ResponseEnum.FILE_DOWNLOAD_URL_GEN_FAIL, e);
        }
    }
}
